package com.syp.hehe.web.controller;

import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.syp.hehe.domain.ArticleTypeEnum;
import com.syp.hehe.domain.vo.ArticleVo;
import com.syp.hehe.domain.vo.CommentVo;
import com.syp.hehe.service.ArticleServiceI;
import com.syp.hehe.service.CommentServiceI;
import com.syp.hehe.service.FavoriteServiceI;
import com.syp.hehe.service.ThumbServiceI;
import com.syp.hehe.util.Constants;
import com.syp.hehe.util.ProcessResult;
import com.syp.hehe.util.SessionInfo;
import com.syp.hehe.util.paging.Page;

@Controller
@RequestMapping("/article")
public class ArticleController {

	private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);

	@Autowired
	private ArticleServiceI articleService;
	@Autowired
	private CommentServiceI commentService;
	@Autowired
	private ThumbServiceI thumbService;
	@Autowired
	private FavoriteServiceI favoriteService;

	@RequestMapping("/{articleType}/tpl")
	public ModelAndView template(@PathVariable(value = "articleType") String articleType) {
		ModelAndView mv = new ModelAndView("/article/list");
		mv.addObject("articleType", articleType);
		return mv;
	}

	@RequestMapping("/list/{articleType}/{pageNum}")
	@ResponseBody
	public ProcessResult list(@PathVariable(value = "articleType") String articleType, @PathVariable("pageNum") Long pageNum) {
		ProcessResult pr = new ProcessResult();
		try {
			pageNum = pageNum == null ? 1L : pageNum;
			Integer type = null;
			if(articleType == null || articleType.equals(ArticleTypeEnum.ALL.getType())){
				type = null;
			}else{
				type = ArticleTypeEnum.getEnum(articleType).getCode();
			}
			
			HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
			SessionInfo sessionInfo = (SessionInfo) session.getAttribute("sessionInfo");
	
			Page<ArticleVo> page = this.articleService.getPageList(type, pageNum, Constants.ARTICLE_PIGE_SIZE);
			for(ArticleVo article: page.getDatas()){
				//评论
				Page<CommentVo> firstPageComments = this.commentService.getPageList(article.getId(), 1L, Constants.COMMENT_PIGE_SIZE);
				article.setComments(firstPageComments);
				//大拇指数量
				Long thumbs = this.thumbService.countOfups(article.getId());
				article.setThumbs(thumbs);
				
				if(sessionInfo != null && StringUtils.isNotEmpty(sessionInfo.getUsername())){
					Boolean curuser_up = this.thumbService.upByUser(sessionInfo.getUsername(), article.getId());
					article.setCuruser_up(curuser_up);					

					Boolean curuser_favorite = this.favoriteService.favoriteByUser(sessionInfo.getUsername(), article.getId());
					article.setCuruser_favorite(curuser_favorite);				
				}
			}
			pr.setSuccess(true);
			pr.setMessage("获取文章列表成功。");
			pr.getRet().put("page", page);
			pr.getRet().put("articleType", articleType);
		} catch (Exception e) {
			logger.error("获取文章列表失败。", e);

			pr.setSuccess(false);
			pr.setMessage("获取文章列表失败。");
		}		
		return pr;
	}

	@RequestMapping(value = "/dpublish")
	@ResponseBody
	public ProcessResult dpublish(@RequestParam MultipartFile pic, ArticleVo article) {
		ProcessResult pr = new ProcessResult();
		try {
			article.setUuid(UUID.randomUUID().toString());

			HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
			SessionInfo sessionInfo = (SessionInfo) session.getAttribute("sessionInfo");
			article.setAuthorUsername(sessionInfo.getUsername());
			
			this.articleService.insert(article);
			pr.setSuccess(true);
			pr.setMessage("投稿成功。");
		} catch (Exception e) {
			logger.error("投稿失败。", e);

			pr.setSuccess(false);
			pr.setMessage("投稿失败。");
		}
		return pr;
	}

	@RequestMapping("/publish/result/tpl")
	public String publish() {
		return "/article/publish.result";
	}
	
	@RequestMapping(value = "/img", method = RequestMethod.GET)
	public void articleImg(Long id, HttpServletResponse response) {
		OutputStream out = null;

		try {
			byte[] picBytes = this.articleService.getPicBytes(id);

			out = new BufferedOutputStream(response.getOutputStream());
			out.write(picBytes);

		} catch (Exception e) {
			logger.error("图片获取失败。", e);
			throw new RuntimeException(e);
		} finally {
			try {
				if (out != null) {
					out.flush();
					out.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
